<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;

class ApiController extends Controller
{
    /**
     * 成功响应
     */
    protected function success($data = null, $message = '操作成功', $code = 200)
    {
        return response()->json([
            'success' => true,
            'message' => $message,
            'data' => $data,
            'code' => $code
        ], $code);
    }

    /**
     * 失败响应
     */
    protected function error($message = '操作失败', $code = 400, $data = null)
    {
        return response()->json([
            'success' => false,
            'message' => $message,
            'data' => $data,
            'code' => $code
        ], $code);
    }

    /**
     * 分页数据格式化
     */
    protected function paginate($paginator, $message = '获取成功')
    {
        return $this->success([
            'data' => $paginator->items(),
            'pagination' => [
                'current_page' => $paginator->currentPage(),
                'last_page' => $paginator->lastPage(),
                'per_page' => $paginator->perPage(),
                'total' => $paginator->total(),
            ]
        ], $message);
    }

    /**
     * 权限检查
     */
    protected function authorizePermission($permission)
    {
        $admin = auth()->user();

        if (!$admin->hasPermission($permission)) {
            abort(403, '权限不足');
        }

        return true;
    }
}
